import { MailOutlined, UserOutlined } from '@ant-design/icons';
import { useRequest, useUnmount } from '@umijs/hooks';
import { Button, Form, Input, message } from 'antd';
import { Store } from 'rc-field-form/lib/interface';
import React, { useEffect, useState } from 'react';
import cookie from "react-cookies";
import { useHistory } from 'react-router';
import { addCookie, editCookie, getCookieValue } from '../../utils/CookieUtil';
import { getRsaSecretString } from '../../utils/encrypt';
import { loginFetch } from '../../utils/Request';
import { url } from '../../utils/url';
import './style.css';

// import useInterval from '../../utils/useInterval';


//类型
interface CountType {
    count: string | number,
    counting: boolean,
    error: "" | "error" | "success" | "warning" | "validating" | undefined,
    message: string | undefined,
}

interface LoginParams {
    phone: string,
    smsCode: string,
    smsToken: string
}

export default function LoginMobileForm() {

    const [data, setData] = useState<CountType>({ count: "", counting: false, error: "", message: undefined })
    // const [timer, settimer] = useState<any>(null)
    const [errorText, seterrorText] = useState<string>("")

    //定时
    let timer: any = null;


    const [form] = Form.useForm();

    const history = useHistory()

    const submit = useRequest(onLogin, { manual: true, loadingDelay: 200 })

    //第一次进来的时候加载  
    useEffect(() => {
        cookie.remove("collegeToken");
        cookie.save("collegeToken", "", { path: "/" });
        const count = getCookieValue("loginMessageSchool")
            ? getCookieValue("loginMessageSchool")
            : 0;
        if (count !== undefined && count > 0) {
            setData({ error: "", message: "", count: count, counting: true })
            timer = setInterval(countDown, 1000)
        }

    }, [])


    //点击提交的时候
    const onFinish = (values: Store) => {

        const value: LoginParams = {
            phone: getRsaSecretString(values.phone) as string,
            smsCode: getRsaSecretString(values.smsCode) as string,
            smsToken: cookie.load(values.phone)
        };
        submit.run(value)
    };

    async function onLogin(params: LoginParams) {
        try {
            const json = await loginFetch(url.LOGIN_MESSAGE_URL, params)
            if (json.success) {
                cookie.remove("collegeToken");
                cookie.save("collegeToken", json.token, { path: "/" })
                cookie.remove(form.getFieldValue("phone"));
                history.push("/homepage");
            } else {
                seterrorText(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }


    //发送短信
    const sendMessage = useRequest(send, {
        manual: true,
        loadingDelay: 200
    });

    //点击发送短信
    async function send() {

        form.validateFields(["phone"])
        const phoneNumber = form.getFieldValue("phone");
        if (!/^1[3456789]\d{9}$/.test(phoneNumber)) {
            setData({ ...data, error: "error", message: "手机号码格式错误" })
        } else {
            const value = { phone: getRsaSecretString(phoneNumber) }
            setData({ ...data, error: "", message: undefined })
            try {
                const json = await loginFetch(url.SEND_MESSAGE, value)
                if (json.success) {
                    cookie.save(phoneNumber, json.smsToken, { path: "/", maxAge: 300 });
                    setData({ error: "", message: "", count: 60, counting: true })
                    addCookie("loginMessageSchool", "60", 60)
                    timer = setInterval(countDown, 1000)
                    cookie.save(phoneNumber, json.smsToken, { path: "/", maxAge: 60 });
                    setInterval(() => console.log(12312), 1000)
                } else {
                    message.destroy();
                    message.error(json.error);
                }

            } catch (error:any) {
                message.destroy();
                message.error(error.message)
            }
        }
    }


    //卸载的时候调用的方法
    useUnmount(() => {
        clearMyInterval(timer);
        // setData({})
    })


    //去除定时任务
    function clearMyInterval(timer: any) {
        if (timer !== null) {
            clearInterval(timer)
        }

    }


    //设置倒计时的信息
    function countDown() {
        let oldCount = getCookieValue("loginMessageSchool");
        let count = 0;
        if (typeof oldCount !== "undefined")
            count = parseInt(oldCount);
        else
            count = 0;
        if (count <= 1) {
            clearMyInterval(timer);
            setData({ ...data, counting: false, count: 0 })
        } else {
            count--;
            setData({ error: "", message: "", count: count, counting: true })
        }
        editCookie("loginMessageSchool", count.toString(), count + 1);
    };

    return (
        <Form
            form={form}
            className="login-form"
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
        >
            <Form.Item
                validateTrigger="onBlur"
                name="phone"
                rules={[{ required: true, message: '请输入手机号!' }, { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' }]}
            >
                <Input prefix={<UserOutlined />} placeholder="手机号码" size="large" />
            </Form.Item>

            <Form.Item
                name="smsCode"
                rules={[{ required: true, message: '请输入短信验证码!' }]}
            >
                <Input prefix={<MailOutlined />} placeholder="短信验证码" size="large" addonAfter={
                    <Button
                        type="link"
                        onClick={sendMessage.run}
                        loading={sendMessage.loading}
                        disabled={data.counting}
                        className={'verification'}
                    >
                        {data.counting ? `${data.count}秒后重发` : "获取验证码"}
                    </Button>
                } />
            </Form.Item>

            <Form.Item >
                <small style={{ color: "red" }}>{errorText}</small>
                <Button type="primary" htmlType="submit" className="login-button" size="large" loading={submit.loading}>
                    登录
        </Button>
            </Form.Item>
        </Form>
    )
}
